package creational.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: RegSingleton
 * @Description: 登记/注册式单例（Spring）
 * @Description: 参考：https://blog.csdn.net/liyanlei5858/article/details/123300948
 * @Author: liu-hao
 * @Date: 2023-04-08 17:23
 * @Version: 1.0
 **/
public class RegSingleton {

    // 单例注册容器
    private static final Map<String, Object> singletonCache = new ConcurrentHashMap();

    // 静态块，在类被加载时自动执行
    static {
        RegSingleton rs = new RegSingleton();
        singletonCache.put(rs.getClass().getName(), rs);
    }

    private RegSingleton() {
    }

    public static Object getInstance(String beanName) {
        if (beanName == null) {
            return null;
        }
        if (singletonCache.get(beanName) == null) {
            try {
                singletonCache.put(beanName, Class.forName(beanName).newInstance());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return singletonCache.get(beanName);
    }
}